import 'dart:async';
import 'dart:ui';
import 'package:canteen/class/order.dart';
import 'package:canteen/constants.dart';
import 'package:canteen/method/find_by_name.dart';
import 'package:canteen/page/calc_page.dart';
import 'package:canteen/userDetail.dart';
import 'package:flutter/material.dart';
import 'package:vibration/vibration.dart';
import 'package:canteen/component/dish_widget.dart';
import 'package:canteen/component/category_widget.dart';
import 'package:canteen/component/animation_ball_widget.dart';
import 'package:canteen/menu_c_v.dart';

class AddOrderPage extends StatefulWidget {
  static const String id = 'add_order_page';

  @override
  State<AddOrderPage> createState() => _AddOrderPageState();
}

class _AddOrderPageState extends State<AddOrderPage> {
  Map<String, int> totalNum = {};
  int active = 0;
  int dishNum = 0;
  bool openBS = false;
  String searchQuery = '';
  final int animationTime = 200;
  List<String> filteredCategory = [];

  void getFilteredCategory() {
    if (user.type == 'ADMIN' || user.type == 'SUPERADMIN') {
      filteredCategory = sortedCategory;
      return;
    }
    filteredCategory =
        sortedCategory.where((element) => element == user.department).toList();
    print(user.department);
  }

  @override
  void didChangeDependencies() {
    // TODO: implement didChangeDependencies
    super.didChangeDependencies();
    getOrder();
    getFilteredCategory();
  }

  void getOrder() {
    final Map<String, dynamic>? args =
        ModalRoute.of(context)?.settings.arguments as Map<String, dynamic>?;
    if (args?['order'] == null) {
      return;
    }
    Order order = args?['order'];
    totalNum = {
      ...order.dishes.map((key, value) => MapEntry(key.name, value)),
      ...order.setMeals.map((key, value) => MapEntry(key.name, value))
    };
    calcDishNum();
  }

  void clearDishes() {
    setState(() {
      totalNum.clear();
      calcDishNum();
      openBS = false;
    });
  }

  void calcDishNum() {
    if (totalNum.isEmpty) {
      dishNum = 0;
      return;
    }
    dishNum =
        totalNum.values.toList().reduce((value, element) => value + element);
    totalNum.removeWhere((key, value) => value == 0);
  }

  void triggerVibration() async {
    // 检查设备是否支持震动
    bool canVibrate = await Vibration.hasVibrator() ?? false;
    if (canVibrate) {
      // 触发一次短震动
      Vibration.vibrate(duration: 100);
    }
  }

  void addDish(dishName, clickPosition) {
    setState(() {
      totalNum[dishName] =
          totalNum.containsKey(dishName) ? totalNum[dishName]! + 1 : 1;

      final RenderBox dishBox = context.findRenderObject() as RenderBox;
      final Offset dishCenter = dishBox.localToGlobal(Offset(
        clickPosition!.dx,
        clickPosition!.dy,
      ));

      final RenderBox bottomBox =
          context.findAncestorRenderObjectOfType<RenderBox>()!;
      final Offset bottomCenter = bottomBox.localToGlobal(Offset(
        70,
        bottomBox.size.height,
      ));

      // 添加动画小球
      final OverlayEntry entry = OverlayEntry(
        builder: (context) => AnimationBallWidget(
          animationTime: animationTime,
          startOffset: dishCenter,
          endOffset: bottomCenter,
        ),
      );
      Overlay.of(context).insert(entry);
      Timer(Duration(milliseconds: animationTime), () {
        setState(() {
          calcDishNum();
          entry.remove();
        });
      });
    });
  }

  List<String> getFilteredDishes() {
    if (searchQuery.isEmpty) {
      try {
        return [
          ...?dishesWithCategory[filteredCategory[active]]?.map((e) => e.name),
          ...?setMealsWithCategory[filteredCategory[active]]?.map((e) => e.name)
        ];
      } catch (e) {
        return [];
      }
    }
    try {
      return [
        ...?dishesWithCategory[filteredCategory[active]]?.map((e) => e.name),
        ...?setMealsWithCategory[filteredCategory[active]]?.map((e) => e.name)
      ]
          .where(
              (dish) => dish.toLowerCase().contains(searchQuery.toLowerCase()))
          .toList();
    } catch (e) {
      return [];
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Color(0xfffbfbfb),
      appBar: AppBar(
        backgroundColor: Color(0xffffffff).withOpacity(0.89),
        elevation: 0,
        centerTitle: true,
        title: Text(
          '点菜',
          style: TextStyle(color: Colors.black, fontSize: 16),
        ),
        leading: GestureDetector(
          onTap: () {
            Navigator.pop(context);
          },
          child: Icon(
            Icons.arrow_back_rounded,
            color: Colors.black,
          ),
        ),
      ),
      body: Stack(
        children: [
          Column(
            children: [
              Container(
                margin:
                    EdgeInsets.only(left: 20, right: 20, bottom: 10, top: 10),
                padding: EdgeInsets.symmetric(horizontal: 15),
                height: 46,
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(25),
                  border: Border.all(color: Colors.black),
                ),
                child: Row(
                  children: [
                    Icon(
                      Icons.search_rounded,
                    ),
                    Expanded(
                      child: TextField(
                        onChanged: (value) {
                          setState(() {
                            searchQuery = value;
                          });
                        },
                        decoration: InputDecoration(
                          hintText: '搜索菜品',
                          border: InputBorder.none,
                        ),
                      ),
                    ),
                  ],
                ),
              ),
              Expanded(
                child: Stack(
                  children: [
                    Row(
                      children: [
                        Expanded(
                          child: Container(
                            clipBehavior: Clip.hardEdge,
                            decoration: BoxDecoration(
                                color: Color(0XFFffffff),
                                borderRadius: active == 0
                                    ? BorderRadius.only(
                                        topLeft: Radius.circular(25),
                                        bottomLeft: Radius.circular(25),
                                        bottomRight: Radius.circular(25))
                                    : BorderRadius.circular(25)),
                            child: ListView.builder(
                              itemCount: filteredCategory.length,
                              itemBuilder: (context, index) {
                                return CategoryWidget(
                                  onClick: () {
                                    setState(() {
                                      active = index;
                                    });
                                  },
                                  active: active,
                                  activeNum: index,
                                  category: filteredCategory[index],
                                );
                              },
                            ),
                          ),
                        ),
                        Expanded(
                          flex: menuFlex,
                          child: Container(
                            margin: EdgeInsets.only(right: 15),
                            decoration: BoxDecoration(
                              border: Border.all(
                                  color: Colors.black.withOpacity(0.5),
                                  width: 2),
                              borderRadius: active == 0
                                  ? BorderRadius.only(
                                      topRight: Radius.circular(25),
                                      bottomLeft: Radius.circular(25),
                                      bottomRight: Radius.circular(25))
                                  : BorderRadius.circular(25),
                              color: Color(0XFFffffff),
                            ),
                            child: AnimatedSwitcher(
                              duration: Duration(milliseconds: 250),
                              child: ListView.builder(
                                key: ValueKey(active),
                                itemCount: getFilteredDishes().length,
                                itemBuilder: (context, index) {
                                  return DishWidget(
                                    dishName: getFilteredDishes()[index],
                                    childWidget: Row(
                                      children: [
                                        GestureDetector(
                                          onTap: () {
                                            if (totalNum[getFilteredDishes()[
                                                    index]] ==
                                                0) {
                                              return;
                                            }
                                            if (totalNum[getFilteredDishes()[
                                                    index]] !=
                                                null) {
                                              setState(() {
                                                totalNum[getFilteredDishes()[
                                                    index]] = totalNum[
                                                        getFilteredDishes()[
                                                            index]]! -
                                                    1;
                                              });
                                            }
                                            calcDishNum();
                                          },
                                          child: Container(
                                            decoration: BoxDecoration(
                                              color: Color(0xffc80815)
                                                  .withOpacity(0.2),
                                              shape: BoxShape.circle,
                                            ),
                                            child: Icon(Icons.remove,
                                                color: Color(0xffc80815)),
                                          ),
                                        ),
                                        Container(
                                          margin: EdgeInsets.symmetric(
                                              horizontal: 6),
                                          padding: EdgeInsets.all(5),
                                          decoration: BoxDecoration(
                                            borderRadius:
                                                BorderRadius.circular(8),
                                            border: Border.all(
                                                color: Colors.black
                                                    .withOpacity(0.2),
                                                width: 0.5),
                                          ),
                                          child: Text(
                                            '${totalNum[getFilteredDishes()[index]] ?? 0}',
                                            style: TextStyle(
                                                fontWeight: FontWeight.bold,
                                                fontSize: 15),
                                          ),
                                        ),
                                        GestureDetector(
                                          onTapUp: (details) {
                                            addDish(getFilteredDishes()[index],
                                                details.globalPosition);
                                          },
                                          child: Container(
                                            decoration: BoxDecoration(
                                              color: Color(0xffc80815),
                                              shape: BoxShape.circle,
                                            ),
                                            child: Icon(
                                              Icons.add,
                                              color: Colors.white,
                                            ),
                                          ),
                                        ),
                                      ],
                                    ),
                                  );
                                },
                              ),
                            ),
                          ),
                        ),
                      ],
                    ),
                    Positioned(
                      left: MediaQuery.of(context).size.width *
                              1 /
                              (menuFlex + 1) -
                          2,
                      top: active * cWHeight + 2,
                      child: Container(
                        width: 4,
                        height: cWHeight - 4,
                        color: Colors.white,
                      ),
                    ),
                  ],
                ),
              ),
              SizedBox(
                height: 65,
              )
            ],
          ),
          Positioned(
            bottom: 0,
            left: 0,
            right: 0,
            child: Column(
              children: [
                AnimatedSwitcher(
                  duration: Duration(milliseconds: 150),
                  transitionBuilder:
                      (Widget child, Animation<double> animation) {
                    return SizeTransition(
                      child: child,
                      sizeFactor: animation,
                    );
                  },
                  child: Container(
                    key: ValueKey<bool>(openBS && dishNum != 0),
                    height: openBS && dishNum != 0 ? 300 : 0,
                    decoration: BoxDecoration(
                      color: Colors.white,
                      borderRadius: BorderRadius.only(
                        topRight: Radius.circular(25),
                        topLeft: Radius.circular(25),
                      ),
                    ),
                    child: Column(
                      children: [
                        Padding(
                          padding: const EdgeInsets.symmetric(
                              vertical: 8.0, horizontal: 20),
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              Text(
                                '品名',
                                style: TextStyle(
                                    fontSize: 18,
                                    color: Color(0xff1b1b1b),
                                    fontWeight: FontWeight.bold),
                              ),
                              Text(
                                '数量',
                                style: TextStyle(
                                    fontSize: 18,
                                    color: Color(0xff1b1b1b),
                                    fontWeight: FontWeight.bold),
                              )
                            ],
                          ),
                        ),
                        Expanded(
                          child: ListView.builder(
                              itemCount: totalNum.length,
                              itemBuilder: (context, index) {
                                return DishWidget(
                                  dishName: totalNum.keys.toList()[index],
                                  childWidget: Row(
                                    children: [
                                      GestureDetector(
                                        onTap: () {
                                          if (user.type != 'ADMIN' &&
                                              user.type != 'SUPERADMIN') {
                                            if (totalNum.values
                                                        .toList()[index] ==
                                                    0 ||
                                                findDishByName(
                                                            totalNum.keys
                                                                    .toList()[
                                                                index],
                                                            allDishes)
                                                        ?.category !=
                                                    user.department) {
                                              return;
                                            }
                                          }
                                          setState(() {
                                            totalNum[totalNum.keys
                                                .toList()[index]] = totalNum[
                                                    totalNum.keys
                                                        .toList()[index]]! -
                                                1;
                                          });
                                          calcDishNum();
                                        },
                                        child: Container(
                                          decoration: BoxDecoration(
                                            color: Color(0xffc80815)
                                                .withOpacity(0.2),
                                            shape: BoxShape.circle,
                                          ),
                                          child: Icon(Icons.remove,
                                              color: Color(0xffc80815)),
                                        ),
                                      ),
                                      Container(
                                        margin:
                                            EdgeInsets.symmetric(horizontal: 6),
                                        padding: EdgeInsets.all(5),
                                        decoration: BoxDecoration(
                                          borderRadius:
                                              BorderRadius.circular(8),
                                          border: Border.all(
                                              color:
                                                  Colors.black.withOpacity(0.2),
                                              width: 0.5),
                                        ),
                                        child: Text(
                                          '${totalNum.values.toList()[index]}',
                                          style: TextStyle(
                                              fontWeight: FontWeight.bold,
                                              fontSize: 15),
                                        ),
                                      ),
                                      GestureDetector(
                                        onTapUp: (details) {
                                          if (user.type != 'ADMIN' &&
                                              user.type != 'SUPERADMIN') {
                                            if (findDishByName(
                                                        totalNum.keys
                                                            .toList()[index],
                                                        allDishes)
                                                    ?.category !=
                                                user.department) {
                                              return;
                                            }
                                          }
                                          addDish(totalNum.keys.toList()[index],
                                              details.globalPosition);
                                        },
                                        child: Container(
                                          decoration: BoxDecoration(
                                            color: Color(0xffc80815),
                                            shape: BoxShape.circle,
                                          ),
                                          child: Icon(
                                            Icons.add,
                                            color: Colors.white,
                                          ),
                                        ),
                                      ),
                                    ],
                                  ),
                                );
                              }),
                        ),
                        user.type == 'ADMIN' || user.type == 'SUPERADMIN'
                            ? GestureDetector(
                                onTap: () {
                                  clearDishes();
                                },
                                child: Padding(
                                  padding: const EdgeInsets.only(top: 12.0),
                                  child: Text(
                                    '清空',
                                    style: TextStyle(
                                        color: Color(0xff1b1b1b),
                                        fontSize: 18,
                                        fontWeight: FontWeight.bold),
                                  ),
                                ),
                              )
                            : SizedBox(),
                      ],
                    ),
                  ),
                ),
                GestureDetector(
                  onTap: () {
                    setState(() {
                      if (dishNum > 0) {
                        openBS = !openBS;
                      }
                    });
                  },
                  child: Container(
                    padding: EdgeInsets.symmetric(horizontal: 30),
                    height: 60,
                    decoration: BoxDecoration(
                      color: Colors.white,
                    ),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Row(
                          children: [
                            Icon(
                              Icons.cloud_queue_rounded,
                              size: 42,
                              color: Color(0xff1b1b1b),
                            ),
                            SizedBox(
                              width: 20,
                            ),
                            Text(
                              '$dishNum个',
                              style: TextStyle(
                                  fontSize: 24, color: Color(0xff1b1b1b)),
                            ),
                          ],
                        ),
                        GestureDetector(
                          onTap: () {
                            Map<String, int> setMealsNum = {};
                            Map<String, int> dishesNum = {};
                            if (dishNum != 0) {
                              totalNum.forEach((key, value) {
                                if (allSetMeals
                                    .map((e) => e.name)
                                    .toList()
                                    .contains(key)) {
                                  setMealsNum.addEntries(
                                      [MapEntry(key, totalNum[key]!)]);
                                } else {
                                  dishesNum.addEntries(
                                      [MapEntry(key, totalNum[key]!)]);
                                }
                              });
                              Navigator.pushNamed(context, CalculatePage.id,
                                  arguments: {
                                    'dishesNum': dishesNum,
                                    'setMealsNum': setMealsNum,
                                  });
                            }
                          },
                          child: AnimatedSwitcher(
                            duration: Duration(milliseconds: 200),
                            child: Container(
                              key: ValueKey<bool>(dishNum != 0),
                              alignment: Alignment.center,
                              width: 100,
                              height: 45,
                              decoration: BoxDecoration(
                                color: dishNum != 0 ? Color(0xffc80815) : null,
                                borderRadius: BorderRadius.circular(25),
                              ),
                              child: Text(
                                dishNum != 0 ? '结算' : '请选择',
                                style: TextStyle(
                                    color: dishNum != 0
                                        ? Colors.white
                                        : Color(0xff1b1b1b),
                                    fontSize: 20,
                                    fontWeight: FontWeight.bold),
                              ),
                            ),
                          ),
                        )
                      ],
                    ),
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }
}
// Positioned.fill(
//   child: CustomPaint(
//     painter: GradientPainter(colorList: [
//       Color(0xffE873FF).withOpacity(0.1),
//       Color(0xffFFC077).withOpacity(0.1),
//     ], xS: 0, yS: 280, heightMul: 0.4),
//   ),
// ),
// BackdropFilter(
//   filter: ImageFilter.blur(sigmaX: 1000, sigmaY: 60),
//   child: Container(),
// ),
